// UploadThread.cpp: implementation of the UploadThread class.
//
//////////////////////////////////////////////////////////////////////

#include "UploadThread.h"
#include "FileDropTargetComponent.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

UploadThread::UploadThread(KetonalConfig *_config, File file, FileDropTargetComponent *_p) : Thread (T("ketonal upload thread"))
{
	config			= _config;
	fileUpload		= new FileUpload();
	parent			= _p;
	fileUpload->addUploadListener (parent);
	currentIndex	= 0;

	XmlElement *formData = config->getFormData();
	Logger::writeToLog (T("uploadThread ctor()"));

	Logger::writeToLog (T("uploadThread set url: ") + config->getUrl());
	fileUpload->setUrl (config->getUrl());

	if (config->isProxyUsed())
	{
		fileUpload->setProxy (config->getProxyUrl());
		fileUpload->setProxyType (config->getProxyType());
	}

	if (formData)
	{
		forEachXmlChildElement (*formData, e)
		{
			if (e->hasTagName (T("HTMLformElement")))
			{
				if (e->getStringAttribute (T("fieldType")) == T("ASK - Input"))
				{
					DialogWindow::showModalDialog (T("Field data needed"), new KetonalInputDialogComponent(e), 0, Colours::white, true, false, false);
				}
			}
		}

		/* do a second loop after asking the user all values */
		forEachXmlChildElement (*formData, e2)
		{
			if (e2->getStringAttribute (T("fieldType")) == T("Input") || e2->getStringAttribute (T("fieldType")) == T("ASK - Input"))
			{
				fileUpload->setFormField (e2->getStringAttribute (T("fieldName")), e2->getStringAttribute (T("fieldValue")));
			}
			if (e2->getStringAttribute (T("fieldType")) == T("File"))
			{
				fileFieldName = e2->getStringAttribute (T("fieldName"));
				fileUpload->setFormField (fileFieldName, file);
			}
		}
	}
}

UploadThread::~UploadThread()
{
	deleteAndZero (fileUpload);
}

void UploadThread::setFile (File f)
{
	fileUpload->setFormField (fileFieldName, f);
}

void UploadThread::run()
{
	Logger::writeToLog (T("uploadThread run()"));
	if (!fileUpload->post())
	{
		parent->uploadEnded(false, fileUpload->getLastError());

		return;
	}
	else
	{
		parent->uploadEnded(true, String::empty);

		return;
	}
}
